﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace Persistence
{
    public class DocTypeController
    {
        public static DocType getDocTypeById(long vId)
        {
            string sql = "SELECT * FROM doctype WHERE dtid = @id;";
            MySqlCommand cmd = DBConnection.getInstance().createCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            cmd.Parameters.AddWithValue("id", Convert.ToInt16(vId));

            DataTable dt = DBConnection.getInstance().executeSelectCommand(cmd);
            DocType dtype = new DocType();

            dtype.LngId = Convert.ToInt64(dt.Rows[0]["dtid"]);
            dtype.StrType = dt.Rows[0]["dttype"].ToString();

            return dtype;
        }

        //Agrega un registro con un nuevo tipo de documento y devuelve el id del mismo.
        public static long insertDocType(string vDoc)
        { 
            DBConnection dbConn = DBConnection.getInstance();
            //Se crea un comando.
            MySqlCommand comm = dbConn.createCommand();
            //Se le asigna el tipo.
            comm.CommandType = CommandType.StoredProcedure;
            //Se le asigna el nombre del procedimiento almacenado.
            comm.CommandText = "proin_DocType";
            //Se asignan los parametros al comando.
            long uId;
            MySqlParameter outIdParam = new MySqlParameter("@vId", MySqlDbType.Int16)
            {
                Direction = ParameterDirection.Output
            };
            comm.Parameters.AddWithValue("@pdttype", truncate(vDoc, 30));
            comm.Parameters.Add(outIdParam);

            dbConn.executeNonQueryCommand(comm);

            uId = long.Parse(outIdParam.Value.ToString());

            return uId;
        }

        public static DataTable getDocTypeList()
        {
            string sql = "SELECT * FROM doctype;";
            //Se crea un comando.
            MySqlCommand comm = DBConnection.getInstance().createCommand();
            //Se le asigna el tipo.
            comm.CommandType = CommandType.Text;
            //Se le asigna la consulta.
            comm.CommandText = sql;
            //Se ejecuta el comando.
            return DBConnection.getInstance().executeSelectCommand(comm);
        }

        private static string truncate(string unSt, int maxLength)
        {
            return unSt.Length <= maxLength ? unSt : unSt.Substring(0, maxLength);
        }
    }
}
